package toolx

import (
	"errors"

	"github.com/asaskevich/govalidator"
	"github.com/ipipdotnet/ipdb-go"
	"github.com/mitchellh/mapstructure"
)

type Region struct {
	Country  string `mapstructure:"country_name"`
	Province string `mapstructure:"region_name"`
	City     string `mapstructure:"city_name"`
}

func Ip2Address(ipv4 string) (reg Region, err error) {
	if !govalidator.IsIPv4(ipv4) {
		err = errors.New("invalid ip;only support IpV4")
		return
	}
	db, err := ipdb.NewCity("assets/ipipfree.ipdb")
	if err != nil {
		return
	}

	data, err := db.FindMap(ipv4, "CN")
	if err != nil {
		return
	}
	err = mapstructure.Decode(data, &reg)
	if err != nil {
		err = errors.New("invalid result")
		return
	}
	return reg, nil
}
